package com.yunshu.yunshuapp.kuaixun;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.OnTapListener;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.user.YSUser;
import com.yunshu.yunshuapp.utils.YSUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class KuaixunSubscribeActivity extends AppCompatActivity implements OnTapListener {

    public static final int REQUEST_CODE = 10001;

    private RecyclerView mRecyclerView;
    private String[] ads;
    private ArrayList<KuaixunChannel> models;
    private TypeListAdapter adapter;
    private YSRequest request;
    private SwipeRefreshLayout swipeRefreshLayout;
    private Handler mExtHandler;
    private static final int MSG_RECYLEVIEW_UPDATE = 100;
    private int pageIndex;

    private Boolean selectionMode = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kuaixun_subscribe);

        NavigationBar navi = (NavigationBar) findViewById(R.id.navigationBar);
        navi.setTitle("请选择类别");
        navi.putInActivity(this);

        if (getIntent().getBooleanExtra("selection", false)) {
            selectionMode = true;
        }

        String title = getIntent().getStringExtra("title");
        if(title != null){
            navi.setTitle("请选择类别");

        }

        addList();
        initLoadMoreListener();
        request = new YSRequest(this);

        this.refresh();
        // this.initLoadMoreListener();
        mExtHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_RECYLEVIEW_UPDATE:
                        adapter.setModels(models);
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };
        Button btn = (Button) findViewById(R.id.button2);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submit();
            }
        });

        if (selectionMode) {
            btn.setVisibility(View.INVISIBLE);
        }
    }

    private void addList() {
        mRecyclerView = (RecyclerView) findViewById(R.id.list_view);
        // use a linear layout manager
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        //设置RecycleView的显示方向：（默认为垂直） 水平
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);

        adapter = new TypeListAdapter(getBaseContext());
        adapter.tapListener = this;
        adapter.activity = this;
        adapter.allowMultiSelect = true;
        mRecyclerView.setAdapter(adapter);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        //设置刷新时动画的颜色，可以设置4个
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }

    private void refresh() {
        if (!request.getIsCompleted()){
            return;
        }
        pageIndex = 1;
        request.GET(YSRequest.Kuaixun_Channels, "&page=1", new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (!result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<KuaixunChannel> temp = new ArrayList<KuaixunChannel>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        KuaixunChannel model = mapper.readValue(jsonstr, KuaixunChannel.class);
                        model.isSelected = isModelSelected(model.getTitle());
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                models = temp;
                pageIndex +=1;
                reloadData();
            }
        });
    }

    public Boolean isModelSelected(String channelId){
        String channelsStr = YSUser.instance().getKuaixunChannels();
        if (channelsStr == null) return  false;
        String[] channels = channelsStr.split(",");
        for ( String id : channels ){
            if (id.equalsIgnoreCase(channelId))
                return true;
        }
        return false;
    }

    private void reloadData() {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                adapter.setModels(models);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void loadmore() {
        request.GET(YSRequest.Kuaixun_Channels,"&page="+pageIndex, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (!result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<KuaixunChannel> temp = new ArrayList<KuaixunChannel>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        KuaixunChannel model = mapper.readValue(jsonstr, KuaixunChannel.class);
                        model.isSelected = isModelSelected(model.getTitle());
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                pageIndex +=1;
                models.addAll( temp);
                reloadData();
            }
        });
    }

    private void initLoadMoreListener() {

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem ;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!request.getIsCompleted()){
                    return;
                }
                //判断RecyclerView的状态 是空闲时，同时，是最后一个可见的ITEM时才加载
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&lastVisibleItem+1==adapter.getItemCount()){

                    loadmore();

                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem=layoutManager.findLastVisibleItemPosition();
            }
        });

    }

    private void endRefreshing() {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(false);
            }
        });


    }

    private void submit(){

        List<KuaixunChannel> items = this.adapter.getModels();
        String idList = "";
        for (KuaixunChannel item : items){
            if (item.isSelected){
                idList += item.getTitle()+",";
            }
        }
        YSUser.instance().setKuaixunChannels(idList);
        YSUser.instance().update(new YSCallback(){

            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                if (isSuccess == YSRequest.REQUEST_OK){
                    YSUtils.showToastOn( KuaixunSubscribeActivity.this ,"定制成功！");
                    finish();
                }
                else{
                    YSUtils.showToastOn( KuaixunSubscribeActivity.this ,"修改失败，请稍后重试！");
                }
            }
        }, this);

    }

    @Override
    public void onSingleTap(View v, int position) {

        if(selectionMode){
            Intent mIntent = new Intent();
            KuaixunChannel newCity = adapter.getModels().get(position);

            mIntent.putExtra("data", newCity.getTitle());

            this.setResult(RESULT_OK,mIntent);
            this.finish();
        }
    }
}
